package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.FindLuggageDataManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.findluggage.service.FindLuggageService;
import com.ias.agdis_r.terminalmanager.restful.findluggage.vo.LuggageMessageVO;
import com.ias.agdis_r.terminalmanager.restful.findluggage.vo.LuggageVO;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by zhaowl on 2018/6/5.
 */
public class FindLuggageActivity extends BaseActivity {

    ListView listView;
    Button btnReport;

    private String taskId;
    private LuggageMessageVO luggageMessage;
    private List<LuggageVO> listLuggage = new ArrayList<>();
    private List<String> templateList = new ArrayList<>();
    private FindLuggageListAdapter luggageListAdapter;
    private ActionBar actionBar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_luggage);
        initActionBar();

        if (!initData()) return;
        initView();
    }

    private void initActionBar() {
        actionBar = getActionBar();
        actionBar.setCustomView(LayoutInflater.from(FindLuggageActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.find_luggage);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FindLuggageActivity.this,
                        MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list_view);
        btnReport = (Button) findViewById(R.id.btn_report);

        luggageListAdapter = new FindLuggageListAdapter(this, listLuggage);
        listView.setAdapter(luggageListAdapter);
        TextView emptyView = (TextView) findViewById(R.id.tv_empty);
        emptyView.setText(R.string.find_luggage_number_empty);
        listView.setEmptyView(emptyView);

        btnReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTemplateDialog(templateList);
            }
        });
    }

    private boolean initData() {
        this.taskId = getIntent().getStringExtra("tnb");
        String messageId = getIntent().getStringExtra("messageId");
        if (TextUtils.isEmpty(taskId) || TextUtils.isEmpty(messageId)) {
            return false;
        }
        luggageMessage = FindLuggageDataManager.getInstance().getLuggageMessageByMsgId(taskId, messageId);
        if (luggageMessage == null) {
            return false;
        }

        listLuggage.clear();
        if (luggageMessage.getLuggages() != null && !luggageMessage.getLuggages().isEmpty()) {
            listLuggage.addAll(luggageMessage.getLuggages());
        }
        templateList.clear();
        if (luggageMessage.getResponseTemplateList() != null && !luggageMessage.getResponseTemplateList().isEmpty()) {
            templateList.addAll(luggageMessage.getResponseTemplateList());
        }

        return true;
    }

    /**
     * 选择回复模板Dialog
     * @param listString 回复模板列表
     */
    private void showTemplateDialog(List<String> listString) {
        if (listString == null || listString.isEmpty()) return;
        final String[] strings = listString.toArray(new String[listString.size()]);

        // 拼接行李号
        final List<LuggageVO> listLuggage = new ArrayList<>();
        LuggageVO luggageChecked;
        final StringBuilder stringBuilder = new StringBuilder();
        SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
        for (int i = 0; i < checkedItemPositions.size(); i++) {
            boolean isChecked = checkedItemPositions.valueAt(i);
            if (isChecked) {
                int index = checkedItemPositions.keyAt(i);
                LuggageVO item = luggageListAdapter.getItem(index);
                luggageChecked = new LuggageVO(item.getLuggageId(), item.getLuggageState());
                listLuggage.add(luggageChecked);

                if (stringBuilder.length() != 0) {
                    stringBuilder.append(",");
                }
                stringBuilder.append(luggageChecked.getLuggageId());
            }
        }

        // 如果有需要填入行李号，则默认选择填入行李号的模板
        int index = listLuggage.isEmpty() ? 0 : hasFillBlank(listString);
        int checkedItem = index > -1 ? index : 0;

        new AlertDialog.Builder(this)
                .setTitle(R.string.find_luggage_select_report_template)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setSingleChoiceItems(strings, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 消息回复模板
                        String template = strings[which];
                        if (template.contains("【】")) {
                            if (listLuggage.isEmpty()) {
                                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.find_luggage_please_select_luggage), false);
                                return;
                            }

                            String start = template.substring(0, template.indexOf("【") + 1);
                            String end = template.substring(template.indexOf("】"), template.length());
                            template = start + stringBuilder.toString() + end;

                            for (LuggageVO vo: listLuggage) {
                                vo.setLuggageFind();
                            }
                        }

                        // 提示确认
                        showReportDialog(template, listLuggage);
                    }
                })
                .setNegativeButton(getString(R.string.cancel), null)
                .show();
    }

    /**
     * 确认上报Dialog
     * @param template 选择的模板（已拼接行李号）
     * @param listLuggage 行李号列表（行李号状态为1）
     */
    private void showReportDialog(final String template, final List<LuggageVO> listLuggage) {
        new AlertDialog.Builder(FindLuggageActivity.this)
                .setTitle(R.string.prompt)
                .setMessage(getString(R.string.find_luggage_confirm_report, template))
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 清除选择
                        listView.clearChoices();
                        // 上报翻行李
                        FindLuggageService.report(taskId, luggageMessage.getMessageId(), template, listLuggage);
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 判断模板是是否包含"【】"
     * @param strings
     * @return
     */
    private int hasFillBlank(List<String> strings) {
        ListIterator<String> listIterator = strings.listIterator(strings.size());
        while (listIterator.hasPrevious()) {
            int index = listIterator.previousIndex();
            String previous = listIterator.previous();
            if (previous.contains("【】")) {
                return index;
            }
        }
        return -1;
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // 上报翻行李成功
        if (MessageModel.FXLR.equals(serviceId)) {
            if (response.getHeader().getStatus() == BaseResponseHeader.STATUS_SUCCESS) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.find_luggage_report_success), false);
                if (initData()) {
                    luggageListAdapter.notifyDataSetChanged();
                }
                return;
            }
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.find_luggage_report_failure), false);
        }
    }

    @Override
    protected void updateUI(String tag) {

    }

    /**
     * 翻行李列表适配器
     */
    private static class FindLuggageListAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        private List<LuggageVO> data;

        public FindLuggageListAdapter(Context context, List<LuggageVO> data) {
            this.data = data;
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public LuggageVO getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private boolean hasFind(int position) {
            LuggageVO item = getItem(position);
            return item != null && item.isLuggageFind();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.layout_find_luggage_item, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            LuggageVO item = getItem(position);
            String luggageId = (item == null || item.getLuggageId() == null) ? "" : item.getLuggageId();
            holder.luggageNoTv.setText(luggageId);
            // 已翻不显示多选
            holder.checkBox.setVisibility(hasFind(position) ? View.GONE : View.VISIBLE);

            return convertView;
        }

        @Override
        public boolean isEnabled(int position) {
            return !hasFind(position);
        }

        private static class ViewHolder {
            TextView luggageNoTv;
            CheckBox checkBox;

            public ViewHolder(View view) {
                luggageNoTv = (TextView) view.findViewById(R.id.tv_luggage_no);
                checkBox = (CheckBox) view.findViewById(R.id.check_box);
            }
        }
    }

}
